package com.ytq.pratice;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author yuantongqin
 * @date 2018/9/9 下午5:05
 */
public class RWLockDemo {

    Map<String,Object> cacheMap = new HashMap<>();
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private Lock read = readWriteLock.readLock();//读锁
    private Lock write = readWriteLock.writeLock();//写锁

    public Object get(String key){
        read.lock();
        //这里调用的是重入锁--》调用非公平锁--》最终实现还是重入锁中lock()

        /**
         if (compareAndSetState(0, 1)) 比较替换，
         //把当前获得锁的线程设置为独占锁
         setExclusiveOwnerThread(Thread.currentThread());
         else
         acquire(1);
         */

        try {
            return cacheMap.get(key);
        }finally {
            read.unlock();
        }
    }

    public Object put(String key,Object value){
        write.lock();
        try {
            return cacheMap.put(key,value);
        }finally {
            write.unlock();
        }
    }


}
